package com.zadtek.jpsqishi.activity;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.zadtek.jpsqishi.frame.MyApplication;
import com.zadtek.jpsqishi.BuildConfig;
import com.zadtek.jpsqishi.R;
import com.zadtek.jpsqishi.activity.common.Common;
import com.zadtek.jpsqishi.activity.common.Const;
import com.zadtek.jpsqishi.activity.data.UserData;
import com.zadtek.jpsqishi.frame.JsonProcessHelper;

import java.io.IOException;

/**
 * 极配送骑士登录界面
 *
 * @author Administrator
 */
@EActivity(R.layout.login)
public class QsLoginActivity extends BaseActivity {

    @ViewById
    ImageView backid; // 返回按钮

    @ViewById
    TextView topview; // 标题

    @ViewById
    EditText log_username, log_passwd; // 用户名,密码

    @ViewById
    Button login_btn; // 登录按钮

    private SharedPreferences sp; // 用户信息缓存
    private Editor editor;

    private Dialog dialog;
    private UserData userdata;
    private TextView get_verifiable_code;
    private EditText register_et_password;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String message = bundle.getString("message");
            switch (msg.what) {
                case 0:
                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    @AfterViews
    void initViews() {
        get_verifiable_code = (TextView) findViewById(R.id.get_verifiable_code);
        register_et_password = (EditText) findViewById(R.id.register_et_password);
        get_verifiable_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = log_username.getText().toString().trim();
                if (name.length() > 0) {
                    countDownTimer.start();
                    getAuthCode(name);
                } else
                    Toast.makeText(getApplicationContext(), "手机号格式不正确", Toast.LENGTH_SHORT).show();

            }
        });
        topview.setText("登录");
        backid.setVisibility(View.GONE);

        if (BuildConfig.DEBUG) {
            log_passwd.setText("111111");
//		    log_username.setText("hyk005");
            log_username.setText("test001");
        }

        // 判断是否已经登录
        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        String uid = sp.getString("uid", "");
        String token = sp.getString("token", "");
        if (uid != null && !uid.equals("") && !TextUtils.isEmpty(token)) {
            Intent intent = new Intent(QsLoginActivity.this, MainActivity.class);
            startActivity(intent);
        }

        for (int i = 0; i < MyApplication.getInstace().getAllActivity().size(); i++) {
            if (!MyApplication.getInstace().getAllActivity().get(i).getClass().getName().contains("QsLoginActivity")) {
                MyApplication.getInstace().getAllActivity().get(i).finish();
            }
        }
        MyApplication.getInstace().getAllActivity().clear();
        MyApplication.getInstace().getAllActivity().add(this);
    }

    /**
     * 获取验证码
     *
     * @param name 用户名
     */
    private void getAuthCode(final String name) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FormBody.Builder builder = new FormBody.Builder()
                        .add("ince", "snscode")
                        .add("uname", name);
                RequestBody requestBody = builder.build();
                Request request = new Request.Builder().url(Const.TOURL).header("Content-Type", "application/x-www-form-urlencoded").post(requestBody).build();
                try {
                    Response response = new OkHttpClient().newCall(request).execute();
                    if (response.isSuccessful()) {
                        String responseData = response.body().string();
                        Log.i("yudan", "获取验证码:" + responseData);
                        JSONObject object = new JSONObject(responseData);
                        String message = object.getString("msg");//返回码
                        Message msg = new Message();
                        msg.what = 0;
                        Bundle bundle = new Bundle();
                        bundle.putString("message", message);
                        msg.setData(bundle);
                        handler.sendMessage(msg);
                    } else {
                        throw new IOException("Unexpected code" + response);
                    }
                } catch (IOException e) {
                    Log.i("yudan", "获取验证码:" + e);
                    closeDialog();
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = 7;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    closeDialog();
                    Log.i("yudan", "获取验证码:" + e);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                super.handleMessage(msg);
                switch (msg.what) {
                    case Const.STATE_START_SUCCESS: // 登录成功
                        closeDialog();
                        userdata = (UserData) msg.obj;
                        String status = userdata.getStatus();
                        if (status != null && status.equals("1")) {
                            Common.DisplayToast(QsLoginActivity.this,
                                    userdata.getMessage(), 1);
                            //恢复激光服务
                            JPushInterface.resumePush(getApplicationContext());
                            // 绑定别名
                            String uid = userdata.getUid();
                            if (!uid.equals("")) {
                                setAlias(uid);
                            }
                            // 登录成功后,将用户信息存入缓存中
                            writeSp();
                            Intent intent = new Intent(QsLoginActivity.this,
                                    MainActivity.class);
                            startActivity(intent);
                        } else {
                            Common.DisplayToast(QsLoginActivity.this,
                                    userdata.getMessage(), 2);
                        }
                        break;
                    case Const.STATE_START_ERROR:
                        closeDialog();
                        Common.DisplayToast(QsLoginActivity.this, "通信失败,请检查网络!", 2);
                        break;
                    case Const.MSG_SET_ALIAS:// 绑定别名
                        JPushInterface.setAliasAndTags(getApplicationContext(),
                                (String) msg.obj, null, mAliasCallback);
                        break;
                }
            }
        };

    }

    // 将用户信息写入缓存中
    private void writeSp() {
        sp = getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
        editor = sp.edit();
        editor.putString("uid", userdata.getUid());
        editor.putString("uname", userdata.getRealname());
        editor.putString("phone", userdata.getPhone());
        editor.putString("account", userdata.getAccount());
        editor.putString("close", userdata.getClose());
        editor.putString("qsstatus", userdata.getQsstatus());
        editor.commit();
    }

    @Click(R.id.login_btn)
    void loginClick() {
        String uname = log_username.getText().toString();
        String upwd = log_passwd.getText().toString();
        if (!"".equals(upwd.trim()) && !"".equals(uname.trim())) {
            String code = register_et_password.getText().toString().trim();
            if (code.length() < 6) {
                Toast.makeText(getApplicationContext(), "请输入正确的验证码", Toast.LENGTH_SHORT).show();
            } else {
                dialog = Common.getTipDialog(QsLoginActivity.this,
                        R.layout.loading, 0, 0);
                new LoginRegAsyncTask().execute("login", uname, upwd, code);
            }
        } else {
            Common.createExitDialog(QsLoginActivity.this, "佰食袋骑士", "请输入用户名和密码!");
        }
    }

    // 关闭dialog
    void closeDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    // 执行登录,注册
    public class LoginRegAsyncTask extends AsyncTask<String, String, String> {

        private UserData user;

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String res = "";
            if (params[0].equals("login")) {
                user = JsonProcessHelper.jsonProcess_user_login("login_qs",
                        params[1], params[2], params[3]);
                if (null != user) {
                    res = "login_ok";
                } else {
                    res = "ping_me_error";
                }

            }

            return res;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (result.equals("login_ok")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_SUCCESS;
                msg.obj = user;
                mHandler.sendMessage(msg);
            } else if (result.equals("ping_me_error")) {
                Message msg = Message.obtain();
                msg.what = Const.STATE_START_ERROR;
                mHandler.sendMessage(msg);
            }
        }

    }

    CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long l) {
            get_verifiable_code.setText(l / 1000 + "秒");
            get_verifiable_code.setClickable(false);
        }

        @Override
        public void onFinish() {
            get_verifiable_code.setText("重新获取");
            get_verifiable_code.setClickable(true);
        }
    };
}
